<?php

namespace app\controller;

use app\common\model\Uploads;
use app\validate\BaseValidate;

class Upload extends ApiController
{
// 文件允许后缀
    protected $fileExt = 'jpg,jpeg,png,gif,bmp4,mp4,mov,avi,wmv,rm,rmvb,mkv,mp3,wma,wav,txt,pdf,doc,docx,
    xls,xlsx,ppt,pptx,zip,rar,tar.gz,gz,heic';
    /*
     * 上传图片
     */
    public function upload()
    {
        try {
            $file = request()->file('__file__');
            $app = 'images';
            if (empty($file) || !$file->isValid()) {
                return self::error(trans('No files uploaded'), 1);
            }
            if (substr($app, 0, 1) == '/') {
                $app = substr($app, 1);
            }
            $rule = [
                'file' => ['fileExt' => $this->fileExt, 'fileSize' => '10485760']  //1024*1024*10  10MB
            ];
            validate(BaseValidate::class)->check($rule);
        } catch (\taoser\exception\ValidateException $e) {
            \support\Log::error('上传失败error'.$e->getError().$e->getFile().$e->getLine());
            return self::error($e->getError(), 1);
        }
        // 是否上传过,上传过直接返回
        $getOriginalName = $file->getUploadName();
        $res = Uploads::field('id,url')->where('name', $getOriginalName)->find();
        if ($res) {
            return self::success(['url' =>  $res['url']], trans('Upload succeeded'), 0);
        }

        $appName = $app.'/'.date('Ymd');
        $fileName = str_replace('.' . $file->getUploadExtension(), '', $file->getUploadName());
        $newFileName = md5($fileName . rand(1000, 9999) . time()).'.'.$file->getUploadExtension();
        $newAppName = '/'.$appName.'/'.$newFileName;
        $uploadPath = public_path().$newAppName;

        $getUploadName = $file->getUploadName();
        $getSize = $file->getSize();
        $getUploadMimeType = $file->getUploadMimeType();
        $getUploadExtension = $file->getUploadExtension();

        $savename = $file->move($uploadPath);
        if ($savename) {
            $imgInfo = getimagesize($uploadPath);
            $insertData = [
                'name' => $getUploadName,
                'url' => $newAppName,
                'file_size' => $getSize,
                'mime_type' => $getUploadMimeType,
                'image_width' => $imgInfo[0],
                'image_height' => $imgInfo[1],
                'ext' => $getUploadExtension,
                'admin_id' => request()->param('admin_id', 0),
                'created_at' => time(),
                'updated_at' => time(),
            ];
            Uploads::create($insertData);
        }

        return self::success(['url' =>  $newAppName], trans('Upload succeeded'), 0);
    }

    /**
     * 富文本上传图片
     * @return \think\response\Json
     */
    public function editUpload()
    {
        try {
            $file = request()->file('edit');
            $app = 'editor';
            if (empty($file)) {
                return self::error(trans('No files uploaded'), 1);
            }
            if (substr($app, 0, 1) == '/') {
                $app = substr($app, 1);
            }
            $rule = [
                'file' => ['fileExt' => $this->fileExt, 'fileSize' => '10485760']  //1024*1024*10  10MB
            ];
            validate(BaseValidate::class)->check($rule);
        } catch (\taoser\exception\ValidateException $e) {
            \support\Log::error('上传失败error'.$e->getError().$e->getFile().$e->getLine());
            return self::error($e->getError(), 1);
        }
        $appName = $app.'/'.date('Ymd');
        $fileName = str_replace('.' . $file->getUploadExtension(), '', $file->getUploadName());
        $newFileName = md5($fileName . rand(1000, 9999) . time()).'.'.$file->getUploadExtension();
        $newAppName = '/'.$appName.'/'.$newFileName;
        $uploadPath = public_path().$newAppName;

        $savename = $file->move($uploadPath);
        return self::success(['url' =>  $savename], trans('Upload succeeded'), 0);
    }

    /**
     * 删除图片
     * @return \think\response\Json|void
     */
    public function delImg()
    {
        $imgUrl = request()->param('del_img', '');
        if (substr($imgUrl, 0, strlen(env('url.base_url'))) == env('url.base_url')) {
            $imgUrl = substr($imgUrl, strlen(env('url.base_url')));
        }
        if (substr($imgUrl, 0, 1) == '/') {
            $imgUrl = substr($imgUrl, 1);
        }
        if (empty($imgUrl)) {
            $code = 1;
            $msg = '删除失败';
        }
        if (!file_exists($imgUrl)) {
            $code = 1;
            $msg = '图片不存在';
        }
        if (unlink($imgUrl)) {
            $code = 0;
            $msg = '删除成功';
        }
        return self::success([], $code, $msg);
    }
}
